<template>
  <div class="p-4">
    <a-card :bordered="false" style="height: 100%">
      <a-tabs v-model:activeKey="activeKey" @change="tabChange">
        <a-tab-pane key="6" tab="Undertow信息"></a-tab-pane>
        <a-tab-pane key="4" tab="磁盘监控">
          <DiskInfo v-if="activeKey == 4" style="height: 100%"></DiskInfo>
        </a-tab-pane>
        <a-tab-pane key="5" tab="内存信息">
          <div v-if="activeKey === '5'" class="flex flex-row h-full">
            <div class="w-1/2" id="jvmPieChart"></div>
            <div class="w-1/2" id="physicalPieChart"></div>
          </div>
        </a-tab-pane>
        <!-- 新增采集器状态标签页 -->
        <a-tab-pane key="7" tab="采集器状态">
          <div v-if="activeKey === '7'" class="collector-status-container">
            <div v-for="(collector, index) in collectorData" :key="index" class="collector-chart-item">
              <h3>{{ collector.name }}</h3>
              <div :id="`collectorChart-${index}`" class="collector-chart"></div>
              <div class="collector-stats">
                <p>总数: {{ collector.num }}</p>
                <p>今日数据量: {{ collector.todayDataNum }}</p>
                <p>历史数据量: {{ collector.historyDataNum }}</p>
              </div>
            </div>
          </div>
        </a-tab-pane>
        <a-tab-pane key="8" tab="mysql信息">
          <div v-if="activeKey === '8'" class="mysql-table-container">
            <BasicTable @register="registerMysqlTable" :dataSource="mysqlTableData" :columns="mysqlTableColumns" :pagination="paginationConfig">
              <template #tableTitle>
                <div>
                  上次更新时间：{{ lastUpdateTime }}
                  <a-divider type="vertical" />
                  <a @click="handleUpdate">立即更新</a>
                  <a-divider type="vertical" />
                  <span>共 {{ mysqlTableData.length }} 张表</span>
                   <a-divider type="vertical" />
    <span>总容量：{{ totalSize.toFixed(2) }} MB</span> 
                </div>
              </template>
            </BasicTable>
          </div>
        </a-tab-pane>
                <a-tab-pane key="9" tab="cpu信息">
          <div v-if="activeKey === '9'" class="cpu-info-container">
            <div class="cpu-stat-card">
              <div class="stat-item">
                <span class="stat-label">CPU核心数</span>
                <span class="stat-value">{{ cpuData.cpuHexinNum }} 核</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">CPU使用率</span>
                <span class="stat-value" :class="{ high: cpuData.cpuUsage > 80 }">
                  {{ (cpuData.cpuUsage * 100).toFixed(2) }}%
                </span>
              </div>
              <div class="update-info">
                上次更新时间：{{ lastUpdateTime }}
                <a-divider type="vertical" />
                <a @click="handleUpdate">立即更新</a>
              </div>
            </div>
          </div>
        </a-tab-pane>
      </a-tabs>

      <BasicTable
        @register="registerTable"
        :searchInfo="searchInfo"
        :dataSource="dataSource"
              v-show="activeKey != 4 && activeKey != 5 && activeKey != '7' && activeKey != '8' && activeKey != '9'"
      >
        <template #tableTitle>
          <div slot="message"
            >上次更新时间：{{ lastUpdateTime }}
            <a-divider type="vertical" />
            <a @click="handleUpdate">立即更新</a></div
          >
        </template>
        <template #param="{ record, text }">
          <a-tag :color="textInfo[record.param].color">{{ text }}</a-tag>
        </template>
        <template #text="{ record }">
          {{ textInfo[record.param].text }}
        </template>
        <template #value="{ record, text }"> {{ text }} {{ textInfo[record.param].unit }} </template>
      </BasicTable>
    </a-card>
  </div>
</template>

<script lang="ts" name="monitor-server" setup>
  import { onMounted, ref, unref, onUnmounted, nextTick } from 'vue';
  import * as echarts from 'echarts';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import DiskInfo from '../disk/DiskInfo.vue';
  import { getServerInfo, getTextInfo, getMoreInfo, getCollectorStatus, getMysqlTableSize,getCpuInfo } from './server.api';
  import { columns } from './server.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import dayjs from 'dayjs';
  // 新增：CPU数据响应式变量
  const cpuData = ref({
    cpuUsage: 0, // CPU使用率（原始值，需转换为百分比）
    cpuHexinNum: 0 // CPU核心数
  });

  const dataSource = ref([]);
  const activeKey = ref('6');
  const moreInfo = ref({});
  const lastUpdateTime = ref({});
  const totalSize = ref(0); // 总容量
  // 新增：mysql表格相关变量
  const mysqlTableData = ref([]); // 存储145条表数据
  const mysqlTableColumns = [
    // 表格列定义
    {
      title: '表名',
      dataIndex: 'TABLE_NAME',
      key: 'TABLE_NAME',
      sorter: (a, b) => a.TABLE_NAME.localeCompare(b.TABLE_NAME), // 支持按表名排序
      ellipsis: true, // 表名过长时省略
    },
    {
      title: '数据容量(MB)',
      dataIndex: 'data_size',
      key: 'data_size',
      sorter: (a, b) => a.data_size - b.data_size, // 支持按数据大小排序
      render: (val) => val.toFixed(6), // 保留6位小数（适配0.015625这类小值）
    },
    {
      title: '索引容量(MB)',
      dataIndex: 'index_size',
      key: 'index_size',
      sorter: (a, b) => a.index_size - b.index_size,
      render: (val) => val.toFixed(6),
    },
    {
      title: '总容量(MB)',
      dataIndex: 'total_size',
      key: 'total_size',
      sorter: (a, b) => a.total_size - b.total_size, // 重点：支持按总大小排序，方便找大表
      render: (val) => val.toFixed(6),
      // 大表标红突出显示（如总容量>100MB）
      cellStyle: (record) => (record.total_size > 100 ? { color: '#f5222d' } : {}),
    },
  ];
  // 分页配置（145条数据分页展示，避免滚动条过长）
  const paginationConfig = ref({
    pageSize: 20, // 每页20条
    showSizeChanger: true, // 允许切换每页条数
    pageSizeOptions: ['10', '20', '50', '100'],
    showTotal: (total) => `共 ${total} 条数据`,
  });
  // 注册mysql表格
  const [registerMysqlTable] = useTable({
    columns: mysqlTableColumns,
    pagination: paginationConfig,
    showIndexColumn: true, // 显示序号列
    bordered: true,
    search: {
      // 支持搜索表名
      labelWidth: 0,
      inputProps: { placeholder: '搜索表名...' },
    },
  });
  let textInfo = ref({});
  const { createMessage } = useMessage();
  // const checkedKeys = ref<Array<string | number>>([]);
  // 新增采集器数据
  const collectorData = ref([]);

  const searchInfo = { logType: '1' };
  const [registerTable, { reload }] = useTable({
    columns,
    showIndexColumn: false,
    bordered: true,
    pagination: false,
    canResize: false,
    tableSetting: { fullScreen: true },
    rowKey: 'id',
  });

  // tab切换
  // tab切换：新增mysql（key=8）的判断
  // Tab切换处理（新增cpu信息判断）
  function tabChange(key) {
    activeKey.value = key;
    if (![1, 2, 3, '4', '7', '8','9'].includes(key)) {
      getInfoList(key);
    }
    if (key === '7') {
      getCollectorData();
    }
    if (key === '8') {
      getMysqlData();
    }
    // 切换到CPU信息时加载数据
    if (key === '9') {
      getCpuData();
    }
  }
 // 新增：获取CPU数据
  function getCpuData() {
    lastUpdateTime.value = dayjs().format('YYYY年MM月DD日 HH时mm分ss秒');
  /*    if (getCpuInfo.success) {
        // 存储原始数据（cpuUsage为小数，如7.705419328673293E-4 → 0.077%）
        cpuData.value = {
          cpuHexinNum: getCpuInfo.result.cpuHexinNum,
          cpuUsage: getCpuInfo.result.cpuUsage // 保留原始小数，展示时再转换为百分比
        };
      } else {
        createMessage.error('获取CPU信息失败');
      } */
    getCpuInfo().then((res) => {
      if (res.success) {
        // 存储原始数据（cpuUsage为小数，如7.705419328673293E-4 → 0.077%）
        cpuData.value = {
          cpuHexinNum: res.result.cpuHexinNum,
          cpuUsage: res.result.cpuUsage // 保留原始小数，展示时再转换为百分比
        };
      } else {
        createMessage.error('获取CPU信息失败');
      }
    });
  }
  // 加载信息
  function getInfoList(infoType) {
    console.log('ppppppp')
    lastUpdateTime.value = dayjs().format('YYYY年MM月DD日 HH时mm分ss秒');
    getServerInfo(infoType).then((res) => {
      textInfo.value = getTextInfo(infoType);
      moreInfo.value = getMoreInfo(infoType);
      let info = [];
      let jvmData = [];
      let physicalData = [];

      if (infoType === '5') {
        for (let param in res[0].result) {
          let data = res[0].result[param];
          let val = convert(data, unref(textInfo)[param].valueType);
          info.push({ id: param, param, text: 'false value', value: val });

          if (param.startsWith('memory.runtime.')) {
            let name = '';
            switch (param) {
              case 'memory.runtime.usage':
                name = 'JVM内存使用率';
                break;
              case 'memory.runtime.free':
                name = 'JVM可用内存';
                break;
              case 'memory.runtime.total':
                name = 'JVM总内存';
                break;
              case 'memory.runtime.used':
                name = 'JVM已使用内存';
                break;
              case 'memory.runtime.max':
                name = 'JVM最大内存';
                break;
            }
            jvmData.push({ name, value: val });
          } else if (param.startsWith('memory.physical.')) {
            let name = '';
            switch (param) {
              case 'memory.physical.free':
                name = '可用物理内存';
                break;
              case 'memory.physical.usage':
                name = '物理内存使用率';
                break;
              case 'memory.physical.total':
                name = '总物理内存';
                break;
              case 'memory.physical.used':
                name = '已使用物理内存';
                break;
            }
            physicalData.push({ name, value: val });
          }
        }
        initJvmPieChart(jvmData);
        initPhysicalPieChart(physicalData);
      } else {
        res.forEach((value, id) => {
          let more = unref(moreInfo)[value.name];
          if (!(more instanceof Array)) {
            more = [''];
          }
          more.forEach((item, idx) => {
            let param = value.name + item;
            let val = convert(value.measurements[idx].value, unref(textInfo)[param].valueType);
            info.push({ id: param + id, param, text: 'false value', value: val });
          });
        });
      }
      dataSource.value = info;
    });
  }

  // 新增：获取采集器数据
  function getCollectorData() {
    lastUpdateTime.value = dayjs().format('YYYY年MM月DD日 HH时mm分ss秒');
    getCollectorStatus().then((res) => {
      if (res.success) {
        collectorData.value = res.result;
        // 等待DOM更新后初始化图表
        nextTick(() => {
          initCollectorCharts();
        });
      } else {
        createMessage.error('获取采集器状态失败');
      }
    });
  }

  // 新增：初始化采集器饼图
  function initCollectorCharts() {
    // 先销毁已存在的图表
    collectorData.value.forEach((_, index) => {
      const chart = echarts.getInstanceByDom(document.getElementById(`collectorChart-${index}`));
      if (chart) {
        chart.dispose();
      }
    });

    // 创建新图表
    collectorData.value.forEach((collector, index) => {
      const chartDom = document.getElementById(`collectorChart-${index}`);
      if (chartDom) {
        const myChart = echarts.init(chartDom);

        // 解析状态数据
        const statusText = collector.status;
        let normal = 0,
          stopped = 0;
        if (statusText.includes('正常：')) {
          normal = parseInt(statusText.match(/正常：(\d+)/)[1]);
        }
        if (statusText.includes('停止：')) {
          stopped = parseInt(statusText.match(/停止：(\d+)/)[1]);
        }
        const option = {
          tooltip: { trigger: 'item' },
          series: [
            {
              name: '状态',
              type: 'pie',
              radius: '70%',
              data: [
                { name: '正常', value: normal, itemStyle: { color: '#52c41a' } },
                { name: '停止', value: stopped, itemStyle: { color: '#f5222d' } },
              ],
              center: ['50%', '50%'],
              emphasis: {
                itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' },
              },
              label: {
                show: true,
                formatter: '{b}: {c} ({d}%)',
              },
            },
          ],
        };

        myChart.setOption(option);
      }
    });
  }

  function getMysqlData() {
    lastUpdateTime.value = dayjs().format('YYYY年MM月DD日 HH时mm分ss秒');
     getMysqlTableSize().then((res) => {
      if (res.success) {
        // 直接将145条数据赋值给表格（保留原始数据）
        mysqlTableData.value = res.result.detail || [];
        // 按总容量降序排序（默认展示时大表在前）
        mysqlTableData.value.sort((a, b) => b.total_size - a.total_size);
      } else {
        createMessage.error('获取mysql表数据失败');
      }
    });
  }
  function initJvmPieChart(data) {
    const chartDom = document.getElementById('jvmPieChart');
    if (chartDom) {
      const myChart = echarts.init(chartDom);
      const option = {
        title: { text: 'JVM内存分布', left: 'center' },
        tooltip: { trigger: 'item' },
        legend: { orient: 'vertical', left: 'left' },
        series: [
          {
            name: 'JVM内存',
            type: 'pie',
            radius: '50%',
            data: data,
            center: ['50%', '50%'],
            emphasis: {
              itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' },
            },
          },
        ],
      };
      myChart.setOption(option);
    }
  }

  function initPhysicalPieChart(data) {
    const chartDom = document.getElementById('physicalPieChart');
    if (chartDom) {
      const myChart = echarts.init(chartDom);
      const option = {
        title: { text: '物理内存分布', left: 'center' },
        tooltip: { trigger: 'item' },
        legend: { orient: 'vertical', left: 'left' },
        series: [
          {
            name: '物理内存',
            type: 'pie',
            radius: '50%',
            data: data,
            center: ['50%', '50%'],
            emphasis: {
              itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' },
            },
          },
        ],
      };
      myChart.setOption(option);
    }
  }

  function handleUpdate() {
    if (activeKey.value === '7') {
      getCollectorData();
    } else if (activeKey.value === '8') {
      getMysqlData();
    } else if (activeKey.value === '9') { // CPU信息刷新
      getCpuData();
    } else {
      getInfoList(activeKey.value);
    }
  }


  // 单位转换
  function convert(value, type) {
    if (type === 'Number') {
      return Number(value * 100).toFixed(2);
    } else if (type === 'Date') {
      return dayjs(value * 1000).format('YYYY-MM-DD HH:mm:ss');
    } else if (type === 'RAM') {
      return Number(value / 1048576).toFixed(3);
    }
    return value;
  }

   // 初始化挂载（新增cpu信息判断）
  onMounted(() => {
    if (activeKey.value === '7') {
      getCollectorData();
    } else if (activeKey.value === '8') {
      getMysqlData();
    } else if (activeKey.value === '9') { // 初始打开CPU标签时加载数据
      getCpuData();
    } else {
      getInfoList(activeKey.value);
    }
  });

  onUnmounted(() => {
    const jvmChart = echarts.getInstanceByDom(document.getElementById('jvmPieChart'));
    const physicalChart = echarts.getInstanceByDom(document.getElementById('physicalPieChart'));
    if (jvmChart) jvmChart.dispose();
    if (physicalChart) physicalChart.dispose();

    // 销毁采集器图表
    collectorData.value.forEach((_, index) => {
      const chart = echarts.getInstanceByDom(document.getElementById(`collectorChart-${index}`));
      if (chart) {
        chart.dispose();
      }
    });
  });
</script>

<style scoped>
  #jvmPieChart,
  #physicalPieChart {
    width: 100%;
    height: 400px;
  }

  .flex-row {
    display: flex;
    flex-direction: row;
    height: calc(100% - 20px);
  }

  /* 新增采集器状态样式 */
  .collector-status-container {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    padding: 10px;
    height: calc(100% - 20px);
    overflow-y: auto;
  }

  .collector-chart-item {
    flex: 1;
    min-width: 300px;
    padding: 15px;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .collector-chart {
    width: 100%;
    height: 200px;
    margin: 10px 0;
  }

  .collector-stats {
    width: 100%;
    text-align: left;
    margin-top: 10px;
  }

  .collector-stats p {
    margin: 5px 0;
    font-size: 14px;
  }
  .mysql-charts-container {
    padding: 10px;
    height: calc(100% - 20px);
    display: flex;
    flex-direction: column;
    gap: 20px;
  }
  .mysql-bar-charts {
    display: flex;
    gap: 20px;
    flex: 1;
  }
  .mysql-chart-item {
    flex: 1;
    min-height: 300px;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    padding: 10px;
  }

  /* 新增：mysql表格容器样式 */
  .mysql-table-container {
    padding: 10px;
    height: calc(100% - 20px);
    overflow: hidden; /* 避免表格超出容器 */
  }
  /* 表格行 hover 效果优化 */
  ::v-deep .ant-table-tbody tr:hover > td {
    background-color: #f5f7fa !important;
  }
  /* 表头样式加粗 */
  ::v-deep .ant-table-thead > tr > th {
    font-weight: 600;
  }

  .cpu-info-container {
    padding: 20px;
    height: calc(100% - 20px);
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .cpu-stat-card {
    width: 100%;
    max-width: 500px;
    padding: 30px;
    border: 1px solid #e8e8e8;
    border-radius: 8px;
    background-color: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  }

  .stat-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25px;
    padding-bottom: 15px;
    border-bottom: 1px dashed #f0f0f0;
  }

  .stat-label {
    font-size: 16px;
    color: #666;
  }

  .stat-value {
    font-size: 24px;
    font-weight: 600;
    color: #1890ff;
  }

  .stat-value.high {
    color: #f5222d; /* 使用率过高时标红 */
  }

  .update-info {
    margin-top: 15px;
    text-align: right;
    font-size: 14px;
    color: #999;
  }
</style>
